package com.baidu.mpks.permission.service;

import com.baidu.mpks.common.RedisClient;
import com.baidu.mpks.role.dto.RoleDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class PermissionCacheServiceImpl implements PermissionCacheService{

    @Value("${permission.cacheExpireTime}")
    int expireTime;
    @Autowired
    RedisClient redisClient;
    private static String cachePrefix = "permission:user:";
    private static String cacheRolePrefix = "permission:role:";
    private static String cachePrefixV3 = "permission:user:V3";
    private static String cacheRolePrefixV3 = "permission:role:V3";

    public PermissionCacheServiceImpl() {
    }

    public void addUserPermission(String userId, Map<String, Map<String, Object>> data) {
        String key = cachePrefix + userId;
        this.redisClient.setKey(key, data, this.expireTime, TimeUnit.MINUTES);
    }

    public void addUserPermissionV3(String userId, Map<String, Object> data) {
        String key = cachePrefixV3 + userId;
        this.redisClient.setKeyV3(key, data, this.expireTime, TimeUnit.MINUTES);
    }

    public void addRolePermission(String roleId, RoleDto data) {
        String key = cacheRolePrefix + roleId;
        this.redisClient.setKey(key, data, this.expireTime, TimeUnit.MINUTES);
    }

    public void clearPermissionAll() {
        this.redisClient.deleteByPattern(cachePrefix + "*");
        this.redisClient.deleteByPattern(cacheRolePrefix + "*");
    }

    public Map<String, Map<String, Object>> getUserPermission(String userId) {
        String key = cachePrefix + userId;
        Map<String, Map<String, Object>> result = this.redisClient.getMapByKey(key);
        return result;
    }

    public Map<String, Object> getUserPermissionV3(String userId) {
        String key = cachePrefixV3 + userId;
        Map<String, Object> result = this.redisClient.getMapByKeyV3(key);
        return result;
    }

    public RoleDto getRolePermission(String roleId) {
        String key = cacheRolePrefix + roleId;
        RoleDto result = this.redisClient.getRoleDtoByKey(key);
        return result;
    }
}
